<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Encapsulates an HTML &lt;select&gt; element.
 * 
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMSelectField extends DMAbstractFormField implements DMFormField {

	private $options = array();


	/**
	 * @return HTML select element
	 * @since 0.4
	 */
	public function getHTMLTag() {
		$dxml = new DMDOMDocument("1.0", "utf-8");
		$dxml->loadXML("<div/>");

		$class = "dmFormField";
		if (!$this->isValid() && $this->isUserData()) {
			$msg = $this->getValidationMessage();
			$dxml->documentElement->appendChild($dxml->createTextNode($msg));
			$class .= " dmInvalid";
		}
		$dxml->documentElement->setAttribute("class", $class);

		$select = $dxml->createElement("select");
		$select->setAttribute("name", $this->getHTMLName());
		foreach ($this->getOptions() as $c) {
			$opt = $dxml->createElement("option",
					DMString::xmlentities($c['label']));
			$opt->setAttribute("value", $c['value']);
			if ($c['value'] == $this->getValue()) {
				$opt->setAttribute("selected", "selected");
			}
			$select->appendChild($opt);
		}
		if (!$this->isEnabled()) {
			$select->setAttribute("disabled", "disabled");
		}
		foreach ($this->getAttributes() as $k => $v) {
			$select->setAttribute($k, $v);
		}
		$dxml->documentElement->appendChild($select);
		return $dxml->saveHTML($dxml->documentElement);
	}

	/**
	 * Adds an &lt;option&gt; element (menu choice) with the specified value
	 * and label.
	 * 
	 * @param string value
	 * @param string label Label of the choice, for option elements
	 * @since 0.4
	 */
	public function addOption($value, $label = null) {
		if (empty($label)) {
			$label = $value;
		}
		$this->options[] = array(
			'value' => $value,
			'label' => $label
		);
	}

	/**
	 * @return array of arrays with 'label' and 'value' keys
	 * @since 0.4
	 * @todo Return an array of DMCPMenuItems instead
	 */
	public function getOptions() {
		return $this->options;
	}

}

